﻿using System;
using System.Collections.Generic;
using System.Linq;
using JT808.DotNetty.Abstractions.Dtos;
using JT808.DotNetty.Core.Interfaces;

namespace JT808.DotNetty.Core.Services
{
    internal class JT808UdpSessionService : IJT808UdpSessionService
    {
        private readonly JT808UdpSessionManager jT808SessionManager;

        public JT808UdpSessionService(
            JT808UdpSessionManager jT808SessionManager)
        {
            this.jT808SessionManager = jT808SessionManager;
        }

        public JT808ResultDto<List<JT808UdpSessionInfoDto>> GetAll()
        {
            JT808ResultDto<List<JT808UdpSessionInfoDto>> resultDto = new JT808ResultDto<List<JT808UdpSessionInfoDto>>();
            try
            {
                resultDto.Data = jT808SessionManager.GetAll().Select(s => new JT808UdpSessionInfoDto
                {
                    LastActiveTime = s.LastActiveTime,
                    StartTime = s.StartTime,
                    TerminalPhoneNo = s.TerminalPhoneNo,
                    RemoteAddressIP = s.Sender.ToString()
                }).ToList();
                resultDto.Code = JT808ResultCode.Ok;
            }
            catch (Exception ex)
            {
                resultDto.Data = null;
                resultDto.Code = JT808ResultCode.Error;
                resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
            }
            return resultDto;
        }

        public JT808ResultDto<bool> RemoveByTerminalPhoneNo(string terminalPhoneNo)
        {
            JT808ResultDto<bool> resultDto = new JT808ResultDto<bool>();
            try
            {
                var session = jT808SessionManager.RemoveSession(terminalPhoneNo);
                if (session != null)
                {
                    if(session.Channel.Open)
                    {
                        session.Channel.CloseAsync();
                    }
                }
                resultDto.Code = JT808ResultCode.Ok;
                resultDto.Data = true;
            }
            catch (AggregateException ex)
            {
                resultDto.Data = false;
                resultDto.Code = 500;
                resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
            }
            catch (Exception ex)
            {
                resultDto.Data = false;
                resultDto.Code = JT808ResultCode.Error;
                resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
            }
            return resultDto;
        }
    }
}
